package com.bobi.tfca.web.resolver;

import cn.hutool.core.lang.Pair;
import com.bobi.tfca.model.entity.MemberEntity;
import com.bobi.tfca.web.annotation.CurrentUser;
import com.bobi.tfca.web.security.Jwt;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Current.class注解拦截器，解析token获取用户信息
 * @author 李文发
 * @date 2024/4/8
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentUser.class) &&
                parameter.getParameterType().isAssignableFrom(MemberEntity.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception {
        // header中获取用户token
        String token = request.getHeader("Authorization");
        MemberEntity user = null;
        if (token != null) {
            Pair<Integer, String> parseJWT = Jwt.parseJWT(token);
            Integer userId = parseJWT.getKey();
            String userName = parseJWT.getValue();
            // 根据userId获取User信息，这里省略，直接创建一个User对象。
            user = new MemberEntity();
            user.setMemberName(userName);
            user.setMemberId(userId);
        }
        return user;
    }
}
